package com.dahai.gameinfo.controller;

import com.dahai.gameinfo.ResultData;
import com.dahai.gameinfo.model.ListData;
import com.dahai.gameinfo.service.DemoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * 文件上传
 */
@RestController()
public class UploadController {
    @Autowired
    DemoService service;
    @Value("${path}")
    private String savePath;


    private static final Logger LOGGER = LoggerFactory.getLogger(UploadController.class);

    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/upload")
    public ResultData upload(@RequestParam("file") MultipartFile file) {
        ResultData result = new ResultData();
        if (file.isEmpty()) {
            result.setState(-1);
            result.setMessage("文件为空");
            return result;
        }

        String fileName = file.getOriginalFilename();
        String filePath = savePath;
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            LOGGER.info("上传成功");
            result.setMessage("上传成功");
            return result;
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
            result.setState(-1);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @PostMapping("/update")
    public String update(@RequestBody ListData listData) {
        if (listData.getPath().isEmpty()) {
            return "修改失敗，path为空";
        }
        System.out.println("id=" + listData.getId() + ",path=" + listData.getPath());
        service.updateListData(listData);
        return "上传失败！";
    }
}


